package com.sy.service;

/**
 * @className: OrdersService
 * @author: Mr.Liu
 * @date: 2025/11/11 16:25
 * @Version: 1.0
 * @description:
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sy.PageVO;
import com.sy.dto.OrdersPageDTO;
import com.sy.mapper.CoursesMapper;
import com.sy.mapper.OrdersMapper;
import com.sy.pojo.Courses;
import com.sy.pojo.Orders;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 订单服务实现类，处理订单创建和状态更新
 */
@Service
@RequiredArgsConstructor
public class OrdersService extends ServiceImpl<OrdersMapper, Orders> {

    private final OrdersMapper ordersMapper;

    private final CoursesMapper coursesMapper;

    /**
     * 创建订单
     *
     * @param userId   用户ID
     * @param courseId 课程ID
     * @param amount   订单金额
     * @return 创建的订单对象
     */
    public Orders createOrder(Integer userId, Integer courseId, BigDecimal amount) {
        // 生成唯一订单号：时间戳 + 随机6位字符（避免重复）
        String orderNumber = "ORD" + System.currentTimeMillis() +
                UUID.randomUUID().toString().substring(0, 6).toUpperCase();
        Orders order = new Orders();
        order.setOrderNumber(orderNumber);  // 订单号
        order.setUserId(userId);            // 用户ID
        order.setCourseId(courseId);        // 课程ID
        order.setAmount(amount);            // 金额
        order.setStatus(0);                 // 初始状态：未支付
        order.setCreateTime(LocalDateTime.now()); // 下单时间
        baseMapper.insert(order); // 保存订单到数据库
        return order;
    }

    /**
     * 更新订单为"已支付"状态
     *
     * @param orderNumber 订单号
     * @return 是否更新成功
     */
    public boolean updateToPaid(String orderNumber) {
        // 查询订单
        Orders order = baseMapper.selectOne(new QueryWrapper<Orders>()
                .eq("order_number", orderNumber));
        if (order == null) return false;

        // 更新状态：已支付（1）、支付方式：支付宝（2）、支付时间
        order.setStatus(1);
        order.setPayMethod(2);
        order.setCheckoutTime(LocalDateTime.now());

        return baseMapper.updateById(order) > 0;
    }

    /*
     * @Author Mr.Liu
     * @Description //TODO 根据用户id和课程id查询该课程是否已经购买
     * @Date 14:49 2025/11/12
     * @Param [userId, coursesId]
     * @return boolean true:已购买  false:未购买
     **/
    public boolean queryOrdersStatusById(Integer userId, Integer coursesId) {
        Orders orders = baseMapper.selectOne(
                new QueryWrapper<Orders>()
                        .eq("user_id", userId)
                        .and(coursesId != null, (qr) -> {
                            qr.eq("course_id", coursesId);
                        })
        );
        if (orders != null) {
            if (orders.getStatus() == 1) {
                return true;
            }
            return false;
        }
        return false;

    }
    /*
     * @Author Mr.Liu
     * @Description //TODO 我的订单的分页查询
     * @Date 15:18 2025/11/13
     * @Param [ordersPageDTO]
     * @return com.sy.PageVO<com.sy.pojo.Orders>
     **/
    public PageVO<Orders> queryByPage(OrdersPageDTO ordersPageDTO){
        //制定分页规范
        PageHelper.startPage(ordersPageDTO.getCurPage(),ordersPageDTO.getPageSize());
        //分页查询
        List<Orders> ordersList = ordersMapper.queryOrdersByUid(
                ordersPageDTO.getUid(),
                ordersPageDTO.getKeyword(),
                ordersPageDTO.getStatus(),
                ordersPageDTO.getStartTime(),
                ordersPageDTO.getEndTime()
        );
        //ordersList有null值属性 courses
        if(ordersList!=null&&ordersList.size()>0){
            for (Orders orders : ordersList) {
                //获取课程id
                Integer courseId = orders.getCourseId();
                //根据课程id查询课程信息
                Courses courses = coursesMapper.selectByPrimaryKey(courseId);
                //将值赋值给对应的属性
                orders.setCourses(courses);
            }
            //构建pageInfo
            PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
            return PageVO.<Orders>builder()
                    .curPage(pageInfo.getPageNum())
                    .pageSize(pageInfo.getPageSize())
                    .total(pageInfo.getTotal())
                    .dataList(pageInfo.getList())
                    .build();
        }
        return null;
    };
}
